import path from 'path'
import { EnvObject, getEnvMode, getEnvObject, getManifest, saveEnvFile, saveManifest, download } from './utils'

export function patchAll(envPrefix: string): void {
  console.log(`
Patching...
`)
  //小程序三个环境票据值
  const ServiceProviderTicketS = {
    VCN: 'gnq76qU7XakxST6WHYPMmj0wimm2FHtxYNep99ofnLgaqaBumkVhBkayIYKQnQ0CMameV2VX6OmQKJ2se4iXhjepb+BZxSMyiaY=',
    DEV: 'EbhQSRkPnvwdjmw0qoSIRtbJmpngyJGv5ut8WVmVm1yrmTlqZfEFniIJ+9xoVrHtLFjNMprH5h9K7ChGvmLs8AsSuPd0SugJ9Qc=',
    PCN: 'PlSSdkMvLg9JKlWvH3Km/FOS3VeNxk8YB2eiiS2c1uhEakPZfsTmA1XJbRtTdXrzkDcaG/qAiFkP7Nmu66hN1veJniyZbjhD0UU=',
  }
  // 获取环境模式 (VCN/PCN/DEV)
  const EnvMode = getEnvMode()
  // 获取环境变量
  let envObject = getEnvObject()

  // 替换构建参数
  envObject = patchEnvArgs(envPrefix, envObject)

  // 获取APPID
  const AppId = envObject['HC_APPID']
  const Version = envObject['HC_VERSION']
  const EnvType = envObject['HC_ENV']
  const ServiceProviderTicket = ServiceProviderTicketS[EnvType]

  if (!AppId) {
    throw new Error('APPID not found')
  }

  // 替换APPID
  patchAppId(AppId, ServiceProviderTicket)

  console.log(`Patch successful

Current APPID:\t${AppId}
Current Environment:\t${EnvMode}
Current Version:\t${Version}
`)
}

/**
 * 动态替换manifest.json中的APPID
 */
export function patchAppId(appId: string, serviceProviderTicket: string) {
  // 读取文件
  const manifest = getManifest()

  if (manifest['mp-weixin'].appid === appId && manifest['mp-weixin'].serviceProviderTicket === serviceProviderTicket) {
    return
  }
  // 修改数据
  manifest['mp-weixin'].appid = appId
  manifest['mp-weixin'].serviceProviderTicket = serviceProviderTicket

  // 写入文件
  saveManifest(manifest)
}

export function patchEnvArgs(envPrefix: string, originEnvObject: EnvObject) {
  const overwriteObject = process.argv.reduce<EnvObject>((argObject, arg) => {
    if (arg.startsWith(envPrefix)) {
      const [key, value] = arg.split('=')
      argObject[key] = value
    }
    return argObject
  }, {})

  const mergedEnvObject = {
    ...originEnvObject,
    ...overwriteObject,
  }
  saveEnvFile(mergedEnvObject)
  return mergedEnvObject
}

export function downloadI18nFile(folderPath: string) {
  let list = [
    {
      url: 'http://52.80.91.107/LiBo//zh_CN.ts',
      targetPath: path.resolve(folderPath, 'zh_CN.ts'),
    },
    {
      url: 'http://52.80.91.107/LiBo//zh_CN.ts',
      targetPath: path.resolve(folderPath, 'zh_CN.ts'),
    },
  ]
  list.map((res) => {
    download(res.url, res.targetPath)
  })
}
